<script setup lang="ts">
  import { h, PropType, ref } from 'vue'
  import { ElDivider } from 'element-plus'
  import handleClipboard from '@/utils/clipboard'
  import { useRouter } from 'vue-router'
  import { usePushDown } from '@/store/modules/pushDown'
  import { useGetOrderDetailGoodListService } from '@/services/module/order/useDetail'
  import UpdateModal from './UpdateModal.vue'

  const { orderDetailGoodList, orderDetailGoodListTotal, getOrderDetailGoodList } =
    useGetOrderDetailGoodListService()
  const { setOrderPushDownInfo } = usePushDown()

  defineOptions({
    name: 'OrderDetailGoodList',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 全局路由对象
  const router = useRouter()

  // 修改弹窗显示状态
  const updateModalVisible = ref(false)

  // 正在修改的商品
  const updatingGood = ref<OrderDetailAPIResponse.GoodListItem>({
    address: '',
    area: '',
    buyMarket: '',
    buyTime: '',
    city: '',
    codes: [],
    endTime: '',
    goodsBrand: '',
    goodsBrandId: '',
    goodsCode: '',
    goodsId: '',
    goodsModel: '',
    goodsName: '',
    goodsSpec: '',
    goodsSpecId: '',
    goodsType: '',
    id: '',
    province: '',
    qty: 0,
    town: '',
    userId: '',
    userName: '',
    userPhone: '',
    repairId: null,
    repairNo: null,
    dl: null,
    specialBz: null,
    standard: null,
    voltage: null,
    xlh: null,
    fuselageImage: null,
    isRelationRepair: 0,
    snCodeImage: null,
    snCodeStatus: null,
    snCodeWarrantyType: null,
    warrantyDay: null,
  })

  /**
   * 修改点击事件
   * @param good - 商品对象
   */
  const handleGoodUpdateClick = (good: OrderDetailAPIResponse.GoodListItem) => {
    updateModalVisible.value = true
    updatingGood.value = good
  }

  /**
   * 下推返厂单点击事件
   * @param good - 商品对象
   */
  const handlePushDownReturnFactory = (good: OrderDetailAPIResponse.GoodListItem) => {
    setOrderPushDownInfo(Object.assign(good, { isStandby: 0 }), props.orderDetail)
    router.push({ path: '/return/factory/new' })
  }

  /**
   * 源返厂单号点击事件
   */
  const onSourceReturnFactoryNoClick = () => {
    router.push({ path: `/return/factory/detail/${props.orderDetail.repairId}` })
  }

  /**
   * 下推返厂单号点击事件
   * @param returnFactoryId - 返厂单id
   */
  const handlePushDownReturnFactoryNoClick = (returnFactoryId: string) => {
    router.push({ path: `/return/factory/detail/${returnFactoryId}` })
  }

  const handleCodeClick = (codeId: string) => {
    router.push(`/code/codetail/${codeId}/${Number(codeId) % 5}`)
  }

  defineExpose({
    tableData: orderDetailGoodList,
    goodList: getOrderDetailGoodList,
  })
</script>

<template>
  <div class="order-detail-good-list">
    <div class="title">设备信息({{ orderDetailGoodListTotal }})</div>
    <el-table
      :border="true"
      :data="orderDetailGoodList"
      resizable
      stripe
      :max-height="300"
      style="width: 100%"
    >
      <!-- 序号 -->
      <el-table-column label="序号" width="50" fixed="left" :align="'center'" type="index" />

      <!-- 合格证 -->
      <el-table-column prop="codes" label="合格证" width="180">
        <template #default="{ row }">
          <span
            v-if="row.codes && row.codes.length > 0"
            style="display: flex; align-items: center; column-gap: 4px"
          >
            <!-- <ShowTooltip
              style="width: calc(100% - 30px)"
              placement="top"
              ref-name="testName"
              class-name="is_textClass"
              :content="(row.codes as OrderDetailAPIResponse.GoodListItem['codes']).map((code) => code.securityCode).join(',') || ''"
              :is-text="true"
              color="#606266"
              :size="12"
              :offset="8"
              :show-after="200"
            ></ShowTooltip> -->
            <h-link
              v-for="(code, codeIndex) in row.codes"
              :key="codeIndex"
              @click="handleCodeClick(code.id)"
            >
              {{ code.securityCode }}
              <template v-if="codeIndex !== row.codes.length - 1">、</template>
            </h-link>
            <h-link
              :data-clipboard-text="(row.codes as OrderDetailAPIResponse.GoodListItem['codes']).map((item) => item.securityCode).join(',')"
              @click="
                handleClipboard(
                  (row.codes as OrderDetailAPIResponse.GoodListItem['codes'])
                    .map((item) => item.securityCode)
                    .join(','),
                  $event,
                )
              "
            >
              复制
            </h-link>
          </span>
        </template>
      </el-table-column>

      <!-- 合同号 -->
      <el-table-column label="合同号" show-overflow-tooltip width="140">
        <template #default="{ row }">
          {{
            row.codes
              ? (row.codes as OrderDetailAPIResponse.GoodListItem['codes'])
                  .map((code) => code.contractNo)
                  .join('、')
              : ''
          }}
        </template>
      </el-table-column>

      <!-- 源返厂单号 -->
      <el-table-column
        v-if="props.orderDetail.isRelationRepair === 1"
        label="源返厂单号"
        width="140"
      >
        <h-link @click="onSourceReturnFactoryNoClick">{{ props.orderDetail.repairNo }}</h-link>
      </el-table-column>

      <!-- 物料编码 -->
      <el-table-column prop="goodsCode" show-overflow-tooltip label="物料编码" width="140" />

      <!-- 物料名称 -->
      <el-table-column prop="goodsName" show-overflow-tooltip label="物料名称" width="140" />

      <!-- 规格型号 -->
      <el-table-column prop="goodsSpec" show-overflow-tooltip label="规格型号" width="140" />

      <!-- 数量 -->
      <el-table-column prop="qty" label="数量" width="50" />

      <!-- 购买时间 -->
      <el-table-column prop="buyTime" label="购买时间" width="128" />

      <!-- 质保到期 -->
      <el-table-column prop="endTime" label="质保到期" width="128" />

      <!-- 登记信息 -->
      <el-table-column prop="address" show-overflow-tooltip label="登记信息" min-width="140">
        <template #default="{ row }">
          {{ row.userName }}&nbsp;{{ row.userPhone }}&nbsp;
          <span v-if="row.province">{{
            row.province + row.city + row.area + row.town + row.address
          }}</span>
        </template>
      </el-table-column>

      <!-- 下推返厂单号 -->
      <el-table-column show-overflow-tooltip label="下推返厂单号" width="140">
        <template #default="{ row }">
          <h-link
            v-if="row.isRelationRepair === 1"
            @click="handlePushDownReturnFactoryNoClick(row.repairId)"
          >
            {{ row.repairNo }}
          </h-link>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column
        label="操作"
        fixed="right"
        :width="'isRelationRepair' in props.orderDetail ? 150 : 50"
      >
        <template #default="{ row }">
          <el-space :size="0" :spacer="spacer">
            <h-link v-permission="'order_commodity'" @click="handleGoodUpdateClick(row)">
              修改
            </h-link>
            <h-link v-if="row.isRelationRepair === 0" @click="handlePushDownReturnFactory(row)">
              下推返厂单
            </h-link>
            <h-link v-else disabled>已下推返厂单</h-link>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <update-modal
      v-model="updateModalVisible"
      :good="updatingGood"
      :order-detail="props.orderDetail"
      @update="getOrderDetailGoodList(props.orderDetail.id)"
    />
  </div>
</template>

<style scoped lang="scss">
  .order-detail-good-list {
    background-color: #fff;
    padding: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .title {
      font-size: 14px;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid #007cff;
      display: flex;
      align-items: center;
      column-gap: 4px;
    }
  }

  .pro_dra {
    :deep(.el-form-item) {
      margin-bottom: 20px !important;
    }
  }

  .ord_dis {
    display: flex;
    align-items: center;
    gap: 5px;
    justify-content: center;

    .img {
      width: 12px;
      height: 12px;
      cursor: pointer;
    }
  }
</style>
